package com.course.cdspringboot.controller;

import com.course.cdspringboot.mapper.StudentMapper;
import com.course.cdspringboot.mapper.TeacherMapper;
import com.course.cdspringboot.mapper.UserMapper;
import com.course.cdspringboot.security.RoleAccessControl;
import com.course.cdspringboot.util.AESUtil;
import com.course.cdspringboot.util.JwtUtil;
import com.course.cdspringboot.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@CrossOrigin
@RestController
public class UserController {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private TeacherMapper teacherMapper;
    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private RoleAccessControl roleAccessControl;

    // 登录账号密码校验
    @PostMapping("/auth/login")
    public Result login(@RequestBody Map<String, Object> user) throws Exception {
        user.put("password", AESUtil.encrypt((String) user.get("password")));

        Map<String, Object> theUser = userMapper.findByUsernameAndPassword((String) user.get("username"), (String) user.get("password"));
        if (theUser != null) {
            String token = JwtUtil.generateToken((String) user.get("username"));
            Map<String, Object> userRole = userMapper.findRoleByUserId((Long) theUser.get("uid"));
            if (userRole != null) {
                return Result.login_ok().data("token", token).data("user", user.get("username")).data("role", userRole.get("name"));
            }

        }
        return Result.login_error();
    }

    // 管理员添加教师
    @PostMapping("/api/add_teacher")
    public Result addTeacher(@RequestBody Map<String, Object> teacherInfo) throws Exception {
        Long uid = roleAccessControl.checkAccess("ROLE_ADMIN");
        teacherInfo.put("p_password", AESUtil.encrypt((String) teacherInfo.get("p_password")));
        teacherMapper.addTeacher(teacherInfo);
        return Result.insert((int)teacherInfo.get("error_code"), (String)teacherInfo.get("error_msg"));
    }

    // 老师添加学生
    @PostMapping("/api/add_student")
    public Result addStudent(@RequestBody Map<String, Object> studentInfo) throws Exception {
        Long uid = roleAccessControl.checkAccess("ROLE_TEACHER");
        studentInfo.put("p_password", AESUtil.encrypt((String) studentInfo.get("p_password")));
        studentInfo.put("p_teacher_id", uid);
        studentMapper.addStudent(studentInfo);
        return Result.insert((int)studentInfo.get("error_code"), (String)studentInfo.get("error_msg"));
    }

}
